package org.dfzt.config.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * xss攻击过滤器
 * @author furao
 * @desc
 * @date 2020/1/16
 * @package com.dfzt.config.filter
 */
public class XssFilter implements Filter{
    //是否过滤富文本内容
    private static boolean IS_INCLUDE_RICH_TEXT = true;
    private boolean isEncrypt=false;

    public XssFilter(boolean isEncrypt) {
        this.isEncrypt=isEncrypt;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request = new XssHttpServletRequestWrapper(request,IS_INCLUDE_RICH_TEXT,this.isEncrypt);
        //防止js页面获取cookie
        response.setHeader("SET-COOKIE","HttpOnly");
        //SAMEORIGIN：不允许被本域以外的页面嵌入
        response.setHeader("X-Frame-Options","SAMEORIGIN");
        //1; mode=block：启用XSS保护，并在检查到XSS攻击时，停止渲染页面
        response.setHeader("X-XSS-Protection","1; mode=block");
        //这个响应头主要是用来定义页面可以加载哪些资源，减少XSS的发生
        response.setHeader("Content-Security-Policy","img-src 'self'");
        //互联网上的资源有各种类型，通常浏览器会根据响应头的Content-Type字段来分辨它们的类型。通过这个响应头可以禁用浏览器的类型猜测行为
        response.setHeader("X-Content-Type-Options","nosniff");
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
